<?php

class User extends CActiveRecord
{
	/**
	 * The followings are the available columns in table '{{user}}':
	 * @var integer $id
	 * @var string $contract
	 * @var string $username
	 * @var string $password
	 * @var string $balance
	 * @var string $limit
	 * @var string $end_time
	 * @var boolean $is_blocked
	 * @var string $address
	 * @var string $email
	 * @var string $telephon
	 * @var boolean $is_active
	 * @var string $create_time
	 * @var string $update_time
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('contract, username', 'required'),
			array('contract, password', 'length', 'max'=>25),
			array('username, address, email, telephon', 'length', 'max'=>128),
			array('balance, limit', 'length', 'max'=>12),
			//array('end_time', 'type', 'type'=>'datetime', 'datetimeFormat'=>Yii::app()->locale->dateFormat.' '.Yii::app()->locale->timeFormat),
			array('is_blocked, is_active', 'boolean'),
			array('create_time, update_time, end_time', 'unsafe'),//, 'type'=>'datetime', 'datetimeFormat'=>'yyyy-MM-dd hh:mm:ss'),//Yii::app()->locale->dateFormat.' '.Yii::app()->locale->timeFormat),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, contract, username, balance, limit, end_time, is_blocked, address, email, telephon, is_active, create_time, update_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'service'=>array(self::HAS_MANY, 'Service', 'user_id', 'condition'=>'service.is_active=1'/*, 'select'=>'sercive.id'*/),
			'payment_now'=>array(self::STAT, 'Payment', 'user_id', 'condition'=>"DATE_FORMAT(t.payment_date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')",'select'=>'sum(t.payment_sum)'),
			'payacc_now'=>array(self::STAT, 'Payacc', 'user_id', 'condition'=>"DATE_FORMAT(t.work_date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')",'select'=>'sum(t.cost)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('main','Id'),
			'contract' => Yii::t('main','Contract'),
			'username' => Yii::t('main','Username'),
			'password' => Yii::t('main','Password'),
			'balance' => Yii::t('main','Balance'),
			'balanceEnd' => Yii::t('main','Balance'),
			'balanceNow' => Yii::t('main','Balance'),
			'limit' => Yii::t('main','Limit'),
			'end_time' => Yii::t('main','End Time Contract'),		// FIXME End Date
			'is_blocked' => Yii::t('main','Is Blocked'),
			'address' => Yii::t('main','Address'),
			'email' => Yii::t('main','Email'),
			'telephon' => Yii::t('main','Telephon'),
			'is_active' => Yii::t('main','Is Active'),
			'create_time' => Yii::t('main','Create Time'),
			'update_time' => Yii::t('main','Update Time'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria(array('with'=>array('payment_now','payacc_now')));

		$criteria->compare('id',$this->id);

		$criteria->compare('contract',$this->contract,true);

		$criteria->compare('username',$this->username,true);

		$criteria->compare('balance',$this->balance,true);

		$criteria->compare('limit',$this->limit,true);

		$criteria->compare('end_time',$this->end_time,true);

		$criteria->compare('is_blocked',$this->is_blocked);

		$criteria->compare('address',$this->address,true);

		$criteria->compare('email',$this->email,true);

		$criteria->compare('telephon',$this->telephon,true);

		$criteria->compare('is_active',$this->is_active);

		$criteria->compare('create_time',$this->create_time,true);

		$criteria->compare('update_time',$this->update_time,true);

		return new CActiveDataProvider('User', array(
			'criteria'=>$criteria,
			'pagination'=>array('pageSize'=>Setting::get('PerPage')),
		));
	}
	
	public function getBalanceNow()
	{
		return sprintf('%.2f', $this->balance+$this->payment_now-$this->payacc_now);
	}
	
	public function getBalanceEnd($date=null, $isTotal=false, $id=null)
	{
		if (!isset($date)) $date = time();
		$year=date('Y',$date);
		$month=date('m',$date);
		$begin=mktime(0,0,0,$month,1,$year);	//begin
		$end=strtotime("+1month -1day",$begin);	//end
		if ($isTotal) $begin = null;
		
		if (isset($id)) {
			$user=User::model()->findbyPk($id);
			$balance=$user->balance;
			$user_id=$user->id;
		} else {
			$balance=$this->balance;
			$user_id=$this->id;
		}
		
		$sum=floatval($balance) +
			floatval(Payment::getTotalCost($begin, $end, $user_id)) -
			floatval(Payacc::getTotalCost($begin, $end, $user_id));
		
        return sprintf('%.2f', $sum);
	}
	
	public function canChangeBalance($dif = null, $id = null, $date = null)
	{
		return ($this->getBalanceEnd($date, true, $id) - floatval($dif) >= 0);
	}

	public function validatePassword($password)
	{
		return $password===$this->password;
	}

	public function behaviors()
    {
        return array(
			'History' => array(
                'class'=>'application.components.behaviors.HistoryBehavior',
            ),
//            'DateTime' => array(
//				'class'=>'application.components.behaviors.DateTimeBehavior',
//			),
			'OldAttributes' => array(
				'class'=>'application.components.behaviors.OldAttributesBehavior',
			),
            'NotActiveOnDelete' => array(
            	'class'=>'application.components.behaviors.NotActiveOnDeleteBehavior',
            ),
        );
    }
}